<template>
  <div class="grading-detail">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-left">
        <button class="back-btn" @click="goBack">
          <i class="fas fa-arrow-left"></i>
          返回
        </button>
        <div class="exam-info">
          <h1>{{ examTitle }}</h1>
          <span class="exam-meta">批改进度: {{ completedCount }}/{{ totalStudents }}</span>
        </div>
      </div>
      <div class="header-right">
        <button class="btn btn-outline" @click="exportGrades">
          <i class="fas fa-download"></i>
          导出成绩
        </button>
        <button class="btn btn-primary" @click="saveAll">
          <i class="fas fa-save"></i>
          保存全部
        </button>
      </div>
    </header>

    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 左侧学生列表 -->
      <aside class="student-sidebar">
        <div class="sidebar-header">
          <h3>学生列表</h3>
          <div class="student-stats">
            <div class="stat-item">
              <span class="stat-number">{{ totalStudents }}</span>
              <span class="stat-label">总人数</span>
            </div>
            <div class="stat-item">
              <span class="stat-number">{{ completedCount }}</span>
              <span class="stat-label">已完成</span>
            </div>
            <div class="stat-item">
              <span class="stat-number">{{ totalStudents - completedCount }}</span>
              <span class="stat-label">待批改</span>
            </div>
          </div>
        </div>
        
        <div class="filter-section">
          <div class="search-box">
            <div class="search-input-wrapper">
              <i class="search-icon">🔍</i>
              <input 
                v-model="searchKeyword" 
                type="text" 
                placeholder="搜索学生姓名或学号"
                class="search-input"
              >
              <button v-if="searchKeyword" @click="searchKeyword = ''" class="clear-btn">✕</button>
            </div>
          </div>
          
          <div class="filter-controls">
            <div class="filter-group">
              <label>状态筛选</label>
              <select v-model="statusFilter" class="status-filter">
                <option value="">全部状态</option>
                <option value="pending">待批改</option>
                <option value="in_progress">批改中</option>
                <option value="completed">已完成</option>
              </select>
            </div>
            
            <div class="filter-group">
              <label>排序方式</label>
              <select v-model="sortBy" class="sort-filter">
                <option value="name">按姓名</option>
                <option value="id">按学号</option>
                <option value="progress">按进度</option>
                <option value="score">按得分</option>
                <option value="submitTime">按提交时间</option>
              </select>
            </div>
          </div>
        </div>
        
        <div class="student-list">
          <div v-if="filteredStudents.length === 0" class="empty-list">
            <div class="empty-icon">👥</div>
            <p>{{ searchKeyword || statusFilter ? '没有找到匹配的学生' : '暂无学生数据' }}</p>
          </div>
          
          <div 
            v-for="student in filteredStudents" 
            :key="student.studentId"
            :class="['student-item', { 
              active: selectedStudent?.studentId === student.studentId,
              completed: student.gradeStatus === 'completed',
              'in-progress': student.gradeStatus === 'in_progress'
            }]"
            @click="selectStudent(student)"
          >
            <div class="student-avatar">
              <span>{{ student.studentName.charAt(0) }}</span>
            </div>
            
            <div class="student-info">
              <div class="student-name">{{ student.studentName }}</div>
              <div class="student-details">
                <span class="student-id">学号: {{ student.studentId }}</span>
                <span class="submit-time" v-if="student.submitTime">
                  {{ formatSubmitTime(student.submitTime) }}
                </span>
              </div>
            </div>
            
            <div class="student-status">
              <span :class="['status-badge', student.gradeStatus]">
                {{ getStatusText(student.gradeStatus) }}
              </span>
              
              <div class="progress-info">
                <div class="progress-text">
                  <span class="current">{{ student.gradedQuestions }}</span>
                  <span class="separator">/</span>
                  <span class="total">{{ student.totalSubjectiveQuestions }}</span>
                </div>
                <div class="progress-bar">
                  <div 
                    class="progress-fill" 
                    :style="{ 
                      width: (student.gradedQuestions / student.totalSubjectiveQuestions * 100) + '%',
                      backgroundColor: getProgressColor(student.gradeStatus)
                    }"
                  ></div>
                </div>
              </div>
              
              <div class="score-info" v-if="student.currentScore !== null">
                <span class="score">{{ student.currentScore }}分</span>
              </div>
            </div>
            
            <div class="student-actions">
              <button 
                v-if="student.gradeStatus === 'completed'"
                @click.stop="viewStudentReport(student)"
                class="action-btn view-btn"
                title="查看报告"
              >
                📊
              </button>
              <button 
                @click.stop="refreshStudent(student)"
                class="action-btn refresh-btn"
                title="刷新数据"
              >
                🔄
              </button>
            </div>
          </div>
        </div>
        
        <div class="sidebar-footer">
          <button @click="refreshAllStudents" class="refresh-all-btn" :disabled="loading">
            {{ loading ? '刷新中...' : '刷新全部' }}
          </button>
        </div>
      </aside>

      <!-- 中间批改区域 -->
      <section class="grading-panel">
        <div v-if="!selectedStudent" class="empty-state">
          <i class="fas fa-user-graduate"></i>
          <h3>请选择学生开始批改</h3>
          <p>从左侧列表中选择一个学生来查看和批改他们的答案</p>
        </div>

        <div v-else class="grading-content">
          <!-- 学生信息头部 -->
          <div class="student-header">
            <div class="student-details">
              <h2>{{ selectedStudent.studentName }}</h2>
              <div class="meta-info">
                <span class="submit-time">
                  <i class="fas fa-clock"></i>
                  提交时间: {{ formatTime(selectedStudent.submitTime) }}
                </span>
                <span :class="['status-badge', getStatusClass(selectedStudent.gradeStatus)]">
                  {{ getStatusText(selectedStudent.gradeStatus) }}
                </span>
              </div>
            </div>
            <div class="score-summary">
              <div class="current-score">
                <span class="label">当前得分</span>
                <span class="score">{{ selectedStudent.currentScore || 0 }}</span>
              </div>
              <div class="progress-summary">
                <span class="label">批改进度</span>
                <span class="progress">{{ selectedStudent.gradedQuestions }}/{{ selectedStudent.totalSubjectiveQuestions }}</span>
              </div>
              <div class="submit-actions" v-if="selectedStudent.gradeStatus === 'in_progress'">
                <button @click="submitGrading" class="submit-btn" :disabled="submitting">
                  <i class="fas fa-check"></i>
                  {{ submitting ? '提交中...' : '提交批改' }}
                </button>
              </div>
            </div>
          </div>

          <!-- 题目导航 -->
          <div v-if="questions.length > 0" class="question-navigation">
            <button 
              v-for="(question, index) in questions" 
              :key="question.questionId"
              :class="['nav-btn', { active: currentQuestionIndex === index, graded: question.score !== null && question.score !== undefined }]"
              @click="currentQuestionIndex = index"
            >
              题目{{ index + 1 }}
              <span v-if="question.score !== null && question.score !== undefined" class="score-badge">{{ question.score }}分</span>
            </button>
          </div>

          <!-- 题目详情 -->
          <div class="questions-container">
            <div v-if="questions.length === 0" class="loading">
              <i class="fas fa-spinner fa-spin"></i>
              <span>加载题目中...</span>
            </div>
            
            <div v-else-if="currentQuestion" class="question-detail">
              <div class="question-card">
                <!-- 题目头部 -->
                <div class="question-header">
                  <div class="question-info">
                    <span class="question-number">第{{ currentQuestionIndex + 1 }}题</span>
                    <span class="question-type">{{ getQuestionTypeText(currentQuestion.questionType) }}</span>
                    <span class="question-points">满分: {{ currentQuestion.points }}分</span>
                  </div>
                  <div class="question-status">
                    <span v-if="currentQuestion.score !== null" class="scored">
                      <i class="fas fa-check-circle"></i>
                      已批改
                    </span>
                    <span v-else class="unscored">
                      <i class="fas fa-clock"></i>
                      待批改
                    </span>
                  </div>
                </div>

                <!-- 题目内容 -->
                <div class="question-content">
                  <h4>题目:</h4>
                  <div class="content" v-html="currentQuestion.questionContent"></div>
                </div>

                <!-- 参考答案 -->
                <div v-if="currentQuestion.referenceAnswer" class="reference-answer">
                  <h4>参考答案:</h4>
                  <div class="content" v-html="currentQuestion.referenceAnswer"></div>
                </div>

                <!-- 学生答案 -->
                <div class="student-answer">
                  <h4>学生答案:</h4>
                  <div class="answer-content">
                    <div v-if="currentQuestion.answerContent" class="text-answer" v-html="currentQuestion.answerContent"></div>
                    <div v-if="currentQuestion.filePath" class="file-answer">
                      <i class="fas fa-file-alt"></i>
                      <a :href="currentQuestion.filePath" target="_blank">查看附件</a>
                    </div>
                    <div v-if="!currentQuestion.answerContent && !currentQuestion.filePath" class="no-answer">
                      <i class="fas fa-exclamation-triangle"></i>
                      学生未作答
                    </div>
                  </div>
                </div>

                <!-- 评分区域 -->
                <div class="scoring-section">
                  <div class="grading-controls">
                    <div class="score-input">
                      <label>得分</label>
                      <div class="score-control">
                        <input 
                          v-model.number="currentQuestion.score" 
                          type="number" 
                          :min="0" 
                          :max="currentQuestion.points"
                          step="0.5"
                          placeholder="0"
                          @input="handleScoreChange"
                        >
                        <span class="max-score">/ {{ currentQuestion.points }}分</span>
                      </div>
                      <div class="quick-score">
                        <button 
                          v-for="ratio in [0, 0.5, 0.8, 1]" 
                          :key="ratio"
                          @click="setQuickScore(ratio)"
                          class="quick-btn"
                        >
                          {{ ratio === 0 ? '0分' : ratio === 1 ? '满分' : (ratio * currentQuestion.points) + '分' }}
                        </button>
                      </div>
                    </div>
                    
                    <div class="comment-input">
                      <label>评语</label>
                      <textarea 
                        v-model="currentQuestion.comment" 
                        placeholder="请输入评语（可选，最多1000字）"
                        maxlength="1000"
                        @input="handleCommentChange"
                      ></textarea>
                      <div class="char-count">{{ (currentQuestion.comment || '').length }}/1000</div>
                    </div>
                  </div>
                  
                  <div class="grading-actions">
                    <button @click="previousQuestion" :disabled="currentQuestionIndex === 0" class="nav-btn prev">
                      上一题
                    </button>
                    <button @click="saveCurrentGrading" class="save-btn" :disabled="saving">
                      {{ saving ? '保存中...' : '保存' }}
                    </button>
                    <button @click="nextQuestion" :disabled="currentQuestionIndex === questions.length - 1" class="nav-btn next">
                      下一题
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from '@/utils/auth'

export default {
  name: 'GradingDetail',
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    // 响应式数据
    const submissionId = ref(route.params.submissionId)
    const examId = ref(route.query.examId || route.params.submissionId) // 优先从query获取examId
    const examTitle = ref('考试批改')
    const students = ref([])
    const selectedStudent = ref(null)
    const questions = ref([])
    const currentQuestionIndex = ref(0)
    const searchKeyword = ref('')
    const statusFilter = ref('')
    const sortBy = ref('name')
    const loading = ref(false)
    const saving = ref(false)
    const submitting = ref(false)
    const autoSaveTimer = ref(null)
    const examInfo = ref({
      examId: '',
      examName: '',
      totalStudents: 0,
      gradedStudents: 0,
      pendingStudents: 0
    })
    
    // 计算属性
    const totalStudents = computed(() => students.value.length)
    const completedCount = computed(() => 
      students.value.filter(s => s.gradeStatus === 'completed').length
    )
    const currentQuestion = computed(() => {
      return questions.value[currentQuestionIndex.value] || null
    })
    
    const filteredStudents = computed(() => {
      let filtered = [...students.value]
      
      // 搜索过滤
      if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        filtered = filtered.filter(student => 
          student.studentName.toLowerCase().includes(keyword) ||
          student.studentId.toString().includes(keyword)
        )
      }
      
      // 状态过滤
      if (statusFilter.value) {
        filtered = filtered.filter(student => student.gradeStatus === statusFilter.value)
      }
      
      // 排序
      filtered.sort((a, b) => {
        switch (sortBy.value) {
          case 'name':
            return a.studentName.localeCompare(b.studentName)
          case 'id':
            return a.studentId.toString().localeCompare(b.studentId.toString())
          case 'progress':
            const progressA = a.gradedQuestions / a.totalSubjectiveQuestions
            const progressB = b.gradedQuestions / b.totalSubjectiveQuestions
            return progressB - progressA
          case 'score':
            return (b.currentScore || 0) - (a.currentScore || 0)
          case 'submitTime':
            return new Date(b.submitTime || 0) - new Date(a.submitTime || 0)
          default:
            return 0
        }
      })
      
      return filtered
    })
    
    // 方法
    const goBack = () => {
      router.go(-1)
    }
    
    const filterStudents = () => {
      let filtered = students.value
      
      // 按关键词筛选
      if (searchKeyword.value) {
        filtered = filtered.filter(student => 
          student.studentName.toLowerCase().includes(searchKeyword.value.toLowerCase())
        )
      }
      
      // 按状态筛选
      if (statusFilter.value) {
        filtered = filtered.filter(student => student.gradeStatus === statusFilter.value)
      }
      
      filteredStudents.value = filtered
    }
    
    const selectStudent = async (student) => {
      selectedStudent.value = student
      currentQuestionIndex.value = 0
      await loadStudentQuestions(student.studentId)
    }
    
    const getStatusClass = (status) => {
      const statusMap = {
        'ungraded': 'ungraded',
        'partial': 'partial', 
        'completed': 'completed'
      }
      return statusMap[status] || 'ungraded'
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待批改',
        'in_progress': '批改中',
        'completed': '已完成',
        'ungraded': '未批改',
        'partial': '部分批改'
      }
      return statusMap[status] || '未知状态'
    }
    
    const getProgressColor = (status) => {
      const colorMap = {
        'pending': '#f59e0b',
        'in_progress': '#3b82f6',
        'completed': '#10b981'
      }
      return colorMap[status] || '#6b7280'
    }
    
    const formatSubmitTime = (time) => {
      if (!time) return '未提交'
      const date = new Date(time)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) return '刚刚'
      if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
      if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
      if (diff < 604800000) return `${Math.floor(diff / 86400000)}天前`
      
      return date.toLocaleDateString('zh-CN', {
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    const viewStudentReport = (student) => {
      // 查看学生报告功能
      ElMessage.info('查看学生报告功能开发中...')
    }
    
    const refreshStudent = async (student) => {
      try {
        // 刷新单个学生数据
        await loadGradingData()
        ElMessage.success('学生数据已刷新')
      } catch (error) {
        ElMessage.error('刷新失败')
      }
    }
    
    const refreshAllStudents = async () => {
      try {
        loading.value = true
        await loadGradingData()
        ElMessage.success('所有学生数据已刷新')
      } catch (error) {
        ElMessage.error('刷新失败')
      } finally {
        loading.value = false
      }
    }
    
    const clearSearch = () => {
      searchKeyword.value = ''
    }
    
    const updateStudentStatus = () => {
      if (!selectedStudent.value) return
      
      const gradedCount = questions.value.filter(q => q.score !== null && q.score !== undefined).length
      const totalCount = questions.value.length
      
      selectedStudent.value.gradedQuestions = gradedCount
      selectedStudent.value.totalSubjectiveQuestions = totalCount
      selectedStudent.value.currentScore = questions.value.reduce((sum, q) => sum + (q.score || 0), 0)
      
      if (gradedCount === 0) {
        selectedStudent.value.gradeStatus = 'pending'
      } else if (gradedCount === totalCount) {
        selectedStudent.value.gradeStatus = 'completed'
      } else {
        selectedStudent.value.gradeStatus = 'in_progress'
      }
    }
    
    const getProgressPercentage = (student) => {
      if (student.totalSubjectiveQuestions === 0) return 0
      return Math.round((student.gradedQuestions / student.totalSubjectiveQuestions) * 100)
    }
    
    const formatTime = (timeStr) => {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return date.toLocaleString('zh-CN')
    }
    
    const getQuestionTypeText = (type) => {
      const typeMap = {
        'subjective': '主观题',
        'essay': '论述题',
        'analysis': '分析题'
      }
      return typeMap[type] || '主观题'
    }
    
    const handleScoreChange = () => {
      // 清除之前的定时器
      if (autoSaveTimer.value) {
        clearTimeout(autoSaveTimer.value)
      }
      // 设置新的定时器，延迟保存
      autoSaveTimer.value = setTimeout(() => {
        if (currentQuestion.value && (currentQuestion.value.score >= 0 || currentQuestion.value.comment)) {
          autoSaveGrading(currentQuestion.value)
        }
      }, 2000) // 2秒后自动保存
    }
    
    const handleCommentChange = () => {
      // 清除之前的定时器
      if (autoSaveTimer.value) {
        clearTimeout(autoSaveTimer.value)
      }
      // 设置新的定时器，延迟保存
      autoSaveTimer.value = setTimeout(() => {
        if (currentQuestion.value && (currentQuestion.value.score >= 0 || currentQuestion.value.comment)) {
          autoSaveGrading(currentQuestion.value)
        }
      }, 2000) // 2秒后自动保存
    }
    
    const setQuickScore = (ratio) => {
      if (currentQuestion.value) {
        currentQuestion.value.score = Math.round(currentQuestion.value.points * ratio * 2) / 2
        autoSaveGrading(currentQuestion.value)
      }
    }
    
    const previousQuestion = () => {
      if (currentQuestionIndex.value > 0) {
        currentQuestionIndex.value--
      }
    }
    
    const nextQuestion = () => {
      if (currentQuestionIndex.value < questions.value.length - 1) {
        currentQuestionIndex.value++
      }
    }
    
    const saveCurrentGrading = async () => {
      if (currentQuestion.value) {
        await autoSaveGrading(currentQuestion.value)
      }
    }
    
    const updateScore = (question) => {
      // 自动保存评分
      autoSaveGrading(question)
    }
    
    const updateComment = (question) => {
      // 自动保存评语
      autoSaveGrading(question)
    }
    
    const setFullScore = (question) => {
      question.score = question.points
      autoSaveGrading(question)
    }
    
    const setZeroScore = (question) => {
      question.score = 0
      autoSaveGrading(question)
    }
    
    const autoSaveGrading = async (question) => {
      if (!question) return false
      
      try {
        saving.value = true
        // 调用API自动保存单个题目批改结果
        const response = await fetch('/api/grading-ui/auto-save', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${getToken()}`
          },
          body: JSON.stringify({
            studentId: selectedStudent.value?.studentId,
            questionId: question.questionId,
            answerId: question.answerId,
            score: question.score,
            comment: question.comment
          })
        })
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const result = await response.json()
        
        if (result.code === 200) {
          // 更新学生状态
          updateStudentStatus()
          ElMessage.success('保存成功')
          return true
        } else {
          throw new Error(result.message || '保存失败')
        }
      } catch (error) {
        console.error('自动保存失败:', error)
        if (error.message && error.message.includes('已被其他教师批改')) {
          ElMessageBox.confirm(
            '该答案已被其他教师批改，请刷新页面查看最新状态。是否立即刷新？',
            '批改冲突',
            {
              confirmButtonText: '刷新页面',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            window.location.reload()
          }).catch(() => {
            // 用户取消刷新
          })
        } else {
          ElMessage.error(`自动保存失败: ${error.message}`)
        }
        return false
      } finally {
        saving.value = false
      }
    }
    
    // updateStudentStatus 方法已在前面定义，删除重复声明
    
    // 继续其他方法定义
    const continueGrading = () => {
      if (questions.value.length === 0) return
      
      const gradedCount = questions.value.filter(q => q.score !== null).length
      const totalCount = questions.value.length
      
      if (selectedStudent.value) {
        selectedStudent.value.gradedQuestions = gradedCount
        selectedStudent.value.currentScore = questions.value.reduce((sum, q) => sum + (q.score || 0), 0)
      }
      
      if (gradedCount === 0) {
        // 状态更新逻辑
      } else if (gradedCount === totalCount) {
        selectedStudent.value.gradeStatus = 'completed'
      } else {
        selectedStudent.value.gradeStatus = 'partial'
      }
    }
    
    const loadGradingData = async () => {
      try {
        loading.value = true
        // 调用API获取批改界面完整数据
        const response = await fetch(`/api/grading-ui/exam/${examId.value}`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${getToken()}`
          }
        })
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const result = await response.json()
        
        if (result.code === 200 && result.data) {
          const data = result.data
          
          // 更新学生列表数据
          students.value = data.students?.map(student => ({
            ...student,
            avatar: student.studentName?.charAt(0) || 'S',
            statusText: getStatusText(student.gradeStatus),
            progressColor: getProgressColor(student.gradeStatus)
          })) || []
          
          // 更新考试信息
          examTitle.value = data.title || data.examName || '考试批改'
          examId.value = data.examId // 设置examId
          
        } else {
          throw new Error(result.message || '获取数据失败')
        }
        
      } catch (error) {
        console.error('加载批改数据失败:', error)
        ElMessage.error('网络错误，请重试')
      } finally {
        loading.value = false
      }
    }
    
    const loadStudentQuestions = async (studentId) => {
      try {
        // 调用API获取指定学生的主观题详情
        const response = await fetch(`/api/grading-ui/exam/${examId.value}/student/${studentId}/questions`, {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${getToken()}`
          }
        })
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const result = await response.json()
        
        if (result.code === 200 && result.data) {
          questions.value = result.data.map((answer, index) => ({
            questionId: answer.questionId,
            questionContent: answer.questionContent,
            questionType: answer.questionType,
            points: answer.maxScore,
            referenceAnswer: answer.referenceAnswer,
            answerContent: answer.answerContent,
            filePath: answer.filePath,
            answerId: answer.answerId,
            score: answer.score,
            comment: answer.comment || ''
          }))
          
          // 设置当前题目
          if (questions.value.length > 0) {
            currentQuestionIndex.value = 0
          }
        } else {
          throw new Error(result.message || '获取题目失败')
        }
        
      } catch (error) {
        console.error('加载学生答案失败:', error)
        ElMessage.error('网络错误，请重试')
      }
    }
    
    const saveAll = async () => {
      try {
        await ElMessageBox.confirm('确定要保存所有批改结果吗？', '确认保存', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        ElMessage.success('保存成功')
      } catch {
        // 用户取消
      }
    }
    
    const submitGrading = async () => {
      if (!selectedStudent.value) return
      
      try {
        // 检查是否所有题目都已批改
        const ungradedQuestions = questions.value.filter(q => q.score === null || q.score === undefined)
        if (ungradedQuestions.length > 0) {
          await ElMessageBox.confirm(
            `还有 ${ungradedQuestions.length} 道题目未批改，确定要提交吗？未批改的题目将按0分计算。`,
            '确认提交',
            {
              confirmButtonText: '确定提交',
              cancelButtonText: '取消',
              type: 'warning'
            }
          )
        } else {
          await ElMessageBox.confirm(
            `确定要提交 ${selectedStudent.value.studentName} 的批改结果吗？提交后将无法修改。`,
            '确认提交',
            {
              confirmButtonText: '确定提交',
              cancelButtonText: '取消',
              type: 'info'
            }
          )
        }
        
        submitting.value = true
        
        // 调用提交API
        const response = await fetch('/api/grading-ui/submit', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${getToken()}`
          },
          body: JSON.stringify({
            examId: examId.value,
            studentId: selectedStudent.value.studentId
          })
        })
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const result = await response.json()
        
        if (result.code === 200) {
          // 更新学生状态为已完成
          selectedStudent.value.gradeStatus = 'completed'
          
          // 更新学生列表中的状态
          const studentInList = students.value.find(s => s.studentId === selectedStudent.value.studentId)
          if (studentInList) {
            studentInList.gradeStatus = 'completed'
          }
          
          ElMessage.success('提交成功！批改结果已保存。')
        } else {
          throw new Error(result.message || '提交失败')
        }
        
      } catch (error) {
        if (error === 'cancel') {
          // 用户取消提交
          return
        }
        console.error('提交失败:', error)
        ElMessage.error(`提交失败: ${error.message}`)
      } finally {
        submitting.value = false
      }
    }
    
    const exportGrades = async () => {
      try {
        // 检查是否所有学生都已批改完成
        if (completedCount.value < totalStudents.value) {
          const result = await ElMessageBox.confirm(
            `当前批改进度：${completedCount.value}/${totalStudents.value}，还有 ${totalStudents.value - completedCount.value} 名学生未完成批改。\n\n确定要导出当前成绩吗？未批改的学生成绩将显示为空。`,
            '批改未完成提醒',
            {
              confirmButtonText: '确定导出',
              cancelButtonText: '取消',
              type: 'warning',
              dangerouslyUseHTMLString: false
            }
          )
          
          if (!result) {
            return
          }
        }
        
        const response = await fetch(`/api/grade-export/excel/${examId.value}`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${getToken()}`
          }
        })
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }
        
        const blob = await response.blob()
        const url = window.URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `考试成绩_${examTitle.value}.xlsx`
        document.body.appendChild(a)
        a.click()
        window.URL.revokeObjectURL(url)
        document.body.removeChild(a)
        
        ElMessage.success('导出成功')
      } catch (error) {
        if (error === 'cancel') {
          // 用户取消导出
          return
        }
        console.error('导出失败:', error)
        ElMessage.error('导出失败，请重试')
      }
    }
    
    // 生命周期
    onMounted(() => {
      loadGradingData()
    })
    
    // 监听搜索和筛选
    watch([searchKeyword, statusFilter], () => {
      filterStudents()
    })
    
    return {
      examTitle,
      students,
      filteredStudents,
      selectedStudent,
      questions,
      searchKeyword,
      statusFilter,
      sortBy,
      loading,
      totalStudents,
      completedCount,
      currentQuestion,
      currentQuestionIndex,
      saving,
      submitting,
      goBack,
      filterStudents,
      selectStudent,
      getStatusClass,
      getStatusText,
      getProgressColor,
      getProgressPercentage,
      formatTime,
      formatSubmitTime,
      getQuestionTypeText,
      handleScoreChange,
      handleCommentChange,
      setQuickScore,
      previousQuestion,
      nextQuestion,
      saveCurrentGrading,
      updateScore,
      updateComment,
      setFullScore,
      setZeroScore,
      saveAll,
      submitGrading,
      exportGrades,
      viewStudentReport,
      refreshStudent,
      refreshAllStudents
    }
  }
}
</script>

<style scoped>
.grading-detail {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

/* 顶部导航栏 */
.header {
  background: white;
  border-bottom: 1px solid #e5e5e5;
  padding: 16px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  background: white;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
}

.back-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.exam-info h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #262626;
}

.exam-meta {
  font-size: 14px;
  color: #8c8c8c;
}

.header-right {
  display: flex;
  gap: 12px;
}

.btn {
  padding: 8px 16px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-outline {
  background: white;
  border: 1px solid #d9d9d9;
  color: #666;
}

.btn-outline:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.btn-primary {
  background: #1890ff;
  color: white;
}

.btn-primary:hover {
  background: #40a9ff;
}

/* 主内容区 */
.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 学生侧边栏样式 */
.student-sidebar {
  width: 380px;
  background: white;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  height: 100%;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.sidebar-header h3 {
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
}

.student-stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-number {
  display: block;
  font-size: 24px;
  font-weight: 700;
  line-height: 1;
}

.stat-label {
  display: block;
  font-size: 12px;
  opacity: 0.9;
  margin-top: 4px;
}

.filter-section {
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
  background: #f8fafc;
}

.search-box {
  margin-bottom: 16px;
}

.search-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.search-icon {
  position: absolute;
  left: 12px;
  font-size: 14px;
  color: #6b7280;
  z-index: 1;
}

.search-input {
  width: 100%;
  padding: 12px 40px 12px 40px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.2s;
  background: white;
}

.search-input:focus {
  outline: none;
  border-color: #3b82f6;
}

.clear-btn {
  position: absolute;
  right: 8px;
  background: #6b7280;
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s;
}

.clear-btn:hover {
  background: #374151;
}

.filter-controls {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.filter-group {
  display: flex;
  flex-direction: column;
}

.filter-group label {
  font-size: 12px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 6px;
}

.status-filter,
.sort-filter {
  padding: 8px 12px;
  border: 2px solid #e5e7eb;
  border-radius: 6px;
  font-size: 13px;
  background: white;
  transition: border-color 0.2s;
}

.status-filter:focus,
.sort-filter:focus {
  outline: none;
  border-color: #3b82f6;
}

.student-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.empty-list {
  text-align: center;
  padding: 40px 20px;
  color: #6b7280;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.student-item {
  display: flex;
  align-items: center;
  padding: 16px 12px;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
  background: white;
  position: relative;
}

.student-item:hover {
  border-color: #3b82f6;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
  transform: translateY(-1px);
}

.student-item.active {
  border-color: #3b82f6;
  background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.2);
}

.student-item.completed {
  border-left: 4px solid #10b981;
}

.student-item.in-progress {
  border-left: 4px solid #3b82f6;
}

.student-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 16px;
  margin-right: 12px;
  flex-shrink: 0;
}

.student-info {
  flex: 1;
  min-width: 0;
}

.student-name {
  font-weight: 600;
  color: #111827;
  margin-bottom: 4px;
  font-size: 15px;
}

.student-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.student-id {
  font-size: 12px;
  color: #6b7280;
}

.submit-time {
  font-size: 11px;
  color: #9ca3af;
}

.student-status {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
  margin-right: 8px;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.status-badge.pending {
  background: #fef3c7;
  color: #d97706;
}

.status-badge.in_progress {
  background: #dbeafe;
  color: #2563eb;
}

.status-badge.completed {
  background: #d1fae5;
  color: #059669;
}

.progress-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 4px;
}

.progress-text {
  font-size: 12px;
  font-weight: 600;
  color: #374151;
}

.progress-text .current {
  color: #059669;
}

.progress-text .separator {
  color: #9ca3af;
  margin: 0 2px;
}

.progress-text .total {
  color: #6b7280;
}

.progress-bar {
  width: 60px;
  height: 6px;
  background: #e5e7eb;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  transition: width 0.3s ease;
  border-radius: 3px;
}

.score-info {
  margin-top: 4px;
}

.score {
  font-weight: 700;
  color: #059669;
  font-size: 13px;
}

.student-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.action-btn {
  width: 28px;
  height: 28px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
}

.view-btn {
  background: #eff6ff;
  color: #2563eb;
}

.view-btn:hover {
  background: #dbeafe;
  transform: scale(1.1);
}

.refresh-btn {
  background: #f3f4f6;
  color: #6b7280;
}

.refresh-btn:hover {
  background: #e5e7eb;
  transform: scale(1.1);
}

.sidebar-footer {
  padding: 16px 20px;
  border-top: 1px solid #e5e7eb;
  background: #f8fafc;
}

.refresh-all-btn {
  width: 100%;
  padding: 12px;
  background: #3b82f6;
  color: white;
  border: none;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.refresh-all-btn:hover:not(:disabled) {
  background: #2563eb;
  transform: translateY(-1px);
}

.refresh-all-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

/* 批改面板 */
.grading-panel {
  flex: 1;
  background: white;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #8c8c8c;
}

.empty-state i {
  font-size: 64px;
  margin-bottom: 16px;
  color: #d9d9d9;
}

.empty-state h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  color: #595959;
}

.empty-state p {
  margin: 0;
  font-size: 14px;
}

.grading-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 学生信息头部 */
.student-header {
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fafafa;
}

.student-details h2 {
  margin: 0 0 8px 0;
  font-size: 20px;
  color: #262626;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 14px;
}

.meta-info i {
  margin-right: 4px;
}

.status-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.score-summary {
  display: flex;
  gap: 32px;
  text-align: center;
}

.score-summary .label {
  display: block;
  font-size: 12px;
  color: #8c8c8c;
  margin-bottom: 4px;
}

.score-summary .score {
  font-size: 24px;
  font-weight: 600;
  color: #1890ff;
}

.score-summary .progress {
  font-size: 18px;
  font-weight: 500;
  color: #52c41a;
}

/* 题目导航样式 */
.question-navigation {
  display: flex;
  gap: 8px;
  padding: 16px 20px;
  background: #f8fafc;
  border-bottom: 1px solid #e2e8f0;
  overflow-x: auto;
}

.question-navigation .nav-btn {
  position: relative;
  background: white;
  border: 1px solid #d1d5db;
  padding: 8px 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  white-space: nowrap;
  font-size: 14px;
  min-width: 80px;
}

.question-navigation .nav-btn:hover {
  border-color: #3b82f6;
  background: #eff6ff;
}

.question-navigation .nav-btn.active {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.question-navigation .nav-btn.graded {
  background: #dcfce7;
  border-color: #16a34a;
  color: #15803d;
}

.question-navigation .nav-btn.graded.active {
  background: #16a34a;
  color: white;
}

.score-badge {
  display: block;
  font-size: 12px;
  margin-top: 2px;
  opacity: 0.8;
}

/* 题目容器 */
.questions-container {
  flex: 1;
  overflow-y: auto;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  padding: 40px;
  color: #8c8c8c;
}

.question-detail {
  height: 100%;
  display: flex;
  flex-direction: column;
}

/* 题目卡片 */
.question-card {
  background: white;
  padding: 24px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.question-header {
  padding: 16px 20px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.question-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.question-number {
  background: #3b82f6;
  color: white;
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
}

.question-type {
  background: #f3f4f6;
  color: #374151;
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 14px;
}

.question-points {
  color: #059669;
  font-weight: 600;
  font-size: 14px;
}

.question-status .scored {
  color: #52c41a;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.question-status .unscored {
  color: #faad14;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.question-status i {
  margin-right: 4px;
}

/* 题目内容区域 */
.question-content,
.reference-answer,
.student-answer {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
}

.question-content h4,
.reference-answer h4,
.student-answer h4 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
  display: flex;
  align-items: center;
  gap: 8px;
}

.question-content h4::before {
  content: '📝';
}

.reference-answer h4::before {
  content: '✅';
}

.student-answer h4::before {
  content: '📄';
}

.content {
  background: #f9fafb;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  line-height: 1.6;
  min-height: 60px;
}

.reference-answer {
  background: #f6ffed;
}

.answer-content {
  background: #f9fafb;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  min-height: 60px;
}

.text-answer {
  line-height: 1.6;
  color: #595959;
  margin-bottom: 12px;
}

.file-answer {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #3b82f6;
  margin-bottom: 12px;
}

.file-answer a {
  color: #3b82f6;
  text-decoration: none;
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 12px;
  background: #eff6ff;
  border-radius: 6px;
  transition: background-color 0.2s;
}

.file-answer a:hover {
  background: #dbeafe;
}

.no-answer {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px;
  background: #fef2f2;
  color: #dc2626;
  border-radius: 8px;
  font-size: 14px;
  font-style: italic;
}

/* 评分区域 */
.scoring-section {
  background: #f8fafc;
  padding: 24px;
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  margin-top: auto;
}

.grading-controls {
  display: grid;
  grid-template-columns: 1fr 2fr;
  gap: 24px;
  margin-bottom: 20px;
}

.score-input {
  margin-bottom: 16px;
}

.score-input label,
.comment-input label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #374151;
  font-size: 14px;
}

.score-control {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.score-control input {
  width: 100px;
  padding: 10px 12px;
  border: 2px solid #d1d5db;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  text-align: center;
  transition: border-color 0.2s;
}

.score-control input:focus {
  outline: none;
  border-color: #3b82f6;
}

.max-score {
  color: #6b7280;
  font-size: 14px;
  font-weight: 500;
}

.quick-score {
  display: flex;
  gap: 6px;
}

.quick-btn {
  background: #e5e7eb;
  border: none;
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 500;
}

.quick-btn:hover {
  background: #d1d5db;
  transform: translateY(-1px);
}

.comment-input textarea {
  width: 100%;
  padding: 12px;
  border: 2px solid #d1d5db;
  border-radius: 8px;
  resize: vertical;
  min-height: 100px;
  font-family: inherit;
  transition: border-color 0.2s;
}

.comment-input textarea:focus {
  outline: none;
  border-color: #3b82f6;
}

.char-count {
  text-align: right;
  font-size: 12px;
  color: #6b7280;
  margin-top: 4px;
}

.grading-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}

.grading-actions .nav-btn {
  background: #f3f4f6;
  border: 1px solid #d1d5db;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 500;
}

.grading-actions .nav-btn:hover:not(:disabled) {
  background: #e5e7eb;
  transform: translateY(-1px);
}

.grading-actions .nav-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.save-btn {
  background: #3b82f6;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  font-weight: 600;
  font-size: 14px;
}

.save-btn:hover:not(:disabled) {
  background: #2563eb;
  transform: translateY(-1px);
}

.save-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 滚动条样式 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 响应式设计和交互效果 */
@media (max-width: 1200px) {
  .student-sidebar {
    width: 320px;
  }
  
  .grading-panel {
    padding: 16px;
  }
  
  .question-navigation {
    flex-wrap: wrap;
    gap: 8px;
  }
  
  .question-navigation .nav-btn {
    min-width: 40px;
    height: 40px;
  }
}

@media (max-width: 768px) {
  .main-content {
    flex-direction: column;
    height: auto;
  }
  
  .student-sidebar {
    width: 100%;
    height: 50vh;
    border-right: none;
    border-bottom: 1px solid #e5e7eb;
  }
  
  .grading-panel {
    width: 100%;
    height: 50vh;
    padding: 12px;
  }
  
  .sidebar-header {
    padding: 16px;
  }
  
  .sidebar-header h3 {
    font-size: 16px;
  }
  
  .student-stats {
    gap: 12px;
  }
  
  .stat-number {
    font-size: 20px;
  }
  
  .filter-section {
    padding: 16px;
  }
  
  .filter-controls {
    grid-template-columns: 1fr;
    gap: 8px;
  }
  
  .student-item {
    padding: 12px 8px;
  }
  
  .student-avatar {
    width: 32px;
    height: 32px;
    font-size: 14px;
  }
  
  .question-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .question-navigation {
    width: 100%;
    justify-content: flex-start;
  }
  
  .question-navigation .nav-btn {
    min-width: 36px;
    height: 36px;
    font-size: 12px;
  }
  
  .question-content,
  .reference-answer,
  .student-answer {
    padding: 16px;
  }
  
  .grading-controls {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .score-control {
    flex-direction: column;
    align-items: stretch;
  }
  
  .quick-score {
    justify-content: space-between;
  }
  
  .quick-btn {
    flex: 1;
    margin: 0 2px;
  }
}

@media (max-width: 480px) {
  .student-sidebar {
    height: 40vh;
  }
  
  .grading-panel {
    height: 60vh;
    padding: 8px;
  }
  
  .sidebar-header {
    padding: 12px;
  }
  
  .student-stats {
    gap: 8px;
  }
  
  .stat-number {
    font-size: 18px;
  }
  
  .stat-label {
    font-size: 10px;
  }
  
  .filter-section {
    padding: 12px;
  }
  
  .search-input {
    padding: 10px 36px 10px 36px;
    font-size: 13px;
  }
  
  .student-item {
    padding: 10px 6px;
  }
  
  .student-name {
    font-size: 14px;
  }
  
  .student-id,
  .submit-time {
    font-size: 10px;
  }
  
  .question-navigation .nav-btn {
    min-width: 32px;
    height: 32px;
    font-size: 11px;
  }
  
  .question-content,
  .reference-answer,
  .student-answer {
    padding: 12px;
  }
  
  .question-content h4,
  .reference-answer h4,
  .student-answer h4 {
    font-size: 16px;
  }
  
  .content,
  .answer-content {
    padding: 12px;
    font-size: 13px;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

@keyframes shake {
  0%, 100% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(-5px);
  }
  75% {
    transform: translateX(5px);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 提交按钮样式 */
.submit-actions {
  margin-top: 12px;
}

.submit-btn {
  background: linear-gradient(135deg, #52c41a, #389e0d);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(82, 196, 26, 0.3);
}

.submit-btn:hover:not(:disabled) {
  background: linear-gradient(135deg, #389e0d, #237804);
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(82, 196, 26, 0.4);
}

.submit-btn:active:not(:disabled) {
  transform: translateY(0);
  box-shadow: 0 2px 4px rgba(82, 196, 26, 0.3);
}

.submit-btn:disabled {
  background: #d9d9d9;
  color: #999;
  cursor: not-allowed;
  box-shadow: none;
}

.submit-btn i {
  font-size: 12px;
}

/* 应用动画 */
.student-item {
  animation: slideIn 0.3s ease-out;
}

.question-detail {
  animation: fadeIn 0.4s ease-out;
}

.saving {
  animation: pulse 1s infinite;
}

.error {
  animation: shake 0.5s ease-in-out;
}

/* 加载状态 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e5e7eb;
  border-top: 4px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

/* 焦点状态 */
.score-control input:focus {
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.comment-input textarea:focus {
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 禁用状态 */
.score-control input:disabled,
.comment-input textarea:disabled {
  background-color: #f8fafc;
  color: #64748b;
  cursor: not-allowed;
}

/* 成功状态 */
.success-feedback {
  border-color: #10b981 !important;
  background-color: #ecfdf5;
}

/* 错误状态 */
.error-feedback {
  border-color: #ef4444 !important;
  background-color: #fef2f2;
}

/* 过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-enter-active,
.slide-leave-active {
  transition: transform 0.3s ease;
}

.slide-enter-from {
  transform: translateX(-100%);
}

.slide-leave-to {
  transform: translateX(100%);
}
</style>